package com.matrix.draft.juc.day1;

import java.util.concurrent.*;
import java.util.function.Function;

public class Main {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService pool = Executors.newFixedThreadPool(3);
        CompletableFuture future = CompletableFuture.supplyAsync(() -> 123)
                .thenApply((Function<Integer, String>) i -> {
                    printThreadInfo("任务2得到" + i);
                    return String.valueOf(i * 10);
                })
                .thenApply(s -> {
                    printThreadInfo("任务3得到" + s);
                    return s + "666";
                })
                .thenApply(s -> {
                    int i = 1 / 0;
                    printThreadInfo("任务4得到" + s);
                    return Double.valueOf(s) + 3.14;
                })
                .handle((d, e) -> {
                    printThreadInfo("handle1得到 " + d);
                    return d / 100;
                }).handle((d, e) -> {
                    printThreadInfo("handle2得到 " + d);
                    return d / 100;
                })
                .whenComplete((r, e) -> {
                    printThreadInfo("whenComplete得到" + r);
                }).exceptionally(e -> {
                    printThreadInfo("出现异常");
                    printThreadInfo(e);
                    return 888888888.0;
                });


        printThreadInfo("最终结果:" + future.get());

    }

    public static void sleep(int timeout) {
        try {
            TimeUnit.SECONDS.sleep(timeout);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void printThreadInfo(Object msg) {
        System.out.println(Thread.currentThread().getName() + " : " + msg);
    }
}
